import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import home from '@/views/home/home.vue'
import category from '@/views/category/category.vue'
import shopcart from '@/views/shopcart/shopcart.vue'
import user from '@/views/user/user.vue'
import productList from '@/views/product-list/product-list.vue'
import productDetail from '@/views/product-detail/product-detail.vue'
import login from '@/views/login/login.vue'
import profile from '@/views/profile/profile.vue'
import register from '@/views/login/register.vue'
import {store} from '../store/index'


 
// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location, onResolve, onReject) {
//  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
//  return originalPush.call(this, location).catch(err => err)
// }
const routes = [
    {
        path: '/',
        name: 'home',
        component: home,
        children: [
          {//在地址为空时，直接跳转路由
            path:'',
            redirect:'/home'
          }
        ]
      },
    {
        path:'/home',
        component:home,
        meta: {
            index: 1
          }
    },
    {
      path: '/login',
      component: login,
      meta: {
        index: 2
      }
    },
    {
      path:'/register',
      component:register,
    },
    {
        path:'/category',
        component:category
    },
    {
        path:'/shopcart',
        component:shopcart,
        meta: {
          index: 1,
          auth: true
        }
    },
    {
        path:'/user',
        component:user,
        meta: {
          index: 1,
          auth: true
        }
    },
    {
        path:'/product-list',
        component:productList,
        meta: {
            index: 2
          }
    },
    {
        path:'/product',
        component:productDetail,
        meta: {
            index: 3
          }
    },
    {
        path: '/profile',
        component: profile,
        meta: {
          index: 2
        }
    },
    
]


const router = new VueRouter({
    routes
})
router.beforeEach((to, from,next) => {
  // 需要验证的路由
  if (to.meta.auth) {
    // 获取用户登录信息
    const userinfo = store.state.userinfo
    if (userinfo) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 不需要验证的路由
    next()
  }
})
export default router